package com.mianle.userapi.util;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义的 Jackson 对枚举类序列化的处理器
 * <p>
 * <b>创建日期：</b> 2015年7月10日
 * </p>
 * 
 * @author heaixia
 * @since 0.0.1-SNAPSHOT
 */
@SuppressWarnings({ "rawtypes" })
public class DaojiaEnumSerializer extends JsonSerializer<Enum> {

    private static final Logger LOGGER = LoggerFactory.getLogger(DaojiaEnumSerializer.class);

    @Override
    public void serialize(Enum value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        Map<String, String> props = null;
        try {
            props = BeanUtils.describe(value);
            props.remove("class");
            props.remove("declaringClass");
        } catch (Exception e) {
            LOGGER.warn("将枚举类 [" + value.getClass() + "] 使用 jackson 序列化成 JSON 字符串发生错误！", e);
            props = new HashMap<String, String>();
        }
        props.put("name", value.name());
        jgen.writeObject(props);
    }
}
